// Copyright 2021 by 马万里. All rights reserved.
// 开发团队 ：   鸡中之霸
// 开发人员 ：   马万里
// 开发时间 ：   2021/3/3 00:58
// 文件名称 ：   user.go
// 工程名称 ：   seckill
// 开发工具 ：   GoLand
//

package services

import (
	"foreground/datamodels"
	"foreground/repositories"
	"golang.org/x/crypto/bcrypt"
)

type IUserService interface {
	IsPwdSuccess(userName string, pwd string) (user *datamodels.User, isOK bool)
	AddUser(user *datamodels.User) (userId int64, err error)
}

func NewUserService(repository repositories.IUserRepository) IUserService {
	return &UserService{repositories: repository}
}

type UserService struct {
	repositories repositories.IUserRepository
}

func (u *UserService) IsPwdSuccess(userName string, pwd string) (user *datamodels.User, isOK bool) {
	user, err := u.repositories.Select(userName)
	if err != nil {
		return nil, false
	}
	if ValidatePassword(pwd, user.HashPassword) {
		return user, true
	}
	return nil, false
}

func (u *UserService) AddUser(user *datamodels.User) (userId int64, err error) {
	hashed, err := GeneratePassword(user.HashPassword)
	if err != nil {
		return 0, err
	}
	user.HashPassword = string(hashed)
	return u.repositories.Insert(user)
}

func GeneratePassword(userPassword string) (hashed []byte, err error) {
	return bcrypt.GenerateFromPassword([]byte(userPassword), bcrypt.DefaultCost)
}

func ValidatePassword(userPassword string, hashedPassword string) (isOK bool) {
	err := bcrypt.CompareHashAndPassword([]byte(hashedPassword), []byte(userPassword))
	if err != nil {
		return false
	}
	return true
}
